<?php

/**
 * 自动生成 WxEventCupidService
 * 
 * Apps/Common/Service/WxEventCupidService.class.php
 * Zix @ 2015-08-12
 */

namespace Common\Service;

class WxEventCupidService {

  private static $instance;
  
  var $name = '月老来牵线';
  var $type = 'Cupid';
  
  public static function instance() {
    if (self::$instance == null) {
      $instance = new WxEventCupidService();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'name' => '',
      'icon' => '',
      'daily_times' => '5',
      'start_time' => '',
      'end_time' => '',
      'share_text' => '',
      'share_url' => '',
      'login_url' => '',
    );
  }

  function get_by_id($id) {
    $WxEventCupid = M('WxEventCupid');
    $data = $WxEventCupid->find($id);
    return $data ? $data : array();
  }

  function get_by_cond($config) {
    $default = array(
      'page' => 1,
      'page_size' => 6,
      'status' => '',
      'mer_id' => '',
      'count' => FALSE,
      'order' => 'DESC',
      'sort' => 'id',
    );

    $config = extend($config, $default);

    $WxEventCupid = M('WxEventCupid');

    $where = array();

    if (!empty($config['status'])) {
      $where['status'] = $config['status'];
    }

    if (!empty($config['mer_id'])) {
      $where['mer_id'] = $config['mer_id'];
    }
    
    if ($config['count']) {
      return $WxEventCupid->where($where)->count();
    } else {
      $order = $config['sort'] . ' ' . $config['order'];
      $limit = ($config['page'] - 1 ) * $config['page_size'] . ' , ' . $config['page_size'];
      $data = $WxEventCupid
          ->where($where)
          ->limit($limit)->order($order)->select();
      //echo $WxEventCupid->_sql();
      return $data ? $data : array();
    }
  }

  function create($data, $is_ajax = true) {
    $WxEventCupid = M('WxEventCupid');
    $ret = $WxEventCupid->add($data);
    if ($is_ajax) {
      if ($ret) {
        return ajax_arr('添加成功', TRUE, array(
          'id' => $ret
        ));
      } else {
        return ajax_arr('添加失败', FALSE);
      }
    } else {
      if ($ret) {
        return $ret;
      } else {
        return 0;
      }
    }
  }

  function update($id, $data) {
    $WxEventCupid = M('WxEventCupid');

    $ret = $WxEventCupid->where("id = %d", $id)->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete($ids) {
    $WxEventCupid = M('WxEventCupid');
    $ret = $WxEventCupid->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }

  
  function _check_time( $event_data ) {
    //检查日期
    if( strtotime($event_data['start_time']) > time() ) {
      return ajax_arr('活动' . $event_data['start_time'] .'开始' );
    }
    
    if( strtotime($event_data['end_time']) < time() ) {
      return ajax_arr('活动' . $event_data['end_time'] . '结束');
    }
    
    return ajax_arr('ok' , TRUE);
  }
  
  function _check_times( $event_data , $user_id ) {
    //取用户当天总数量
    $WxEventCupidUserService = WxEventCupidUserService::instance();
    if( $event_data['daily_times'] > 0 ) {
      $today_total = $WxEventCupidUserService->get_total_by_event_user($event_data['id'] , $user_id , TRUE );
      
      //检查用户今天已经玩过几次
      if ( $today_total >= $event_data['daily_times'] ) {
        return ajax_arr('宝宝姻缘总不到位，多半是没选对！咱明日再来！');
      }
    }
    
    return ajax_arr('ok'  , TRUE);
  }
  
  function _prepare_user_data( $event_data , $take_award_data , $beauty_id ) {
    $data = array(
      'event_type' => $this->type ,
      'event_id' => $event_data[id] ,
      'award_id' => $take_award_data['id'] ,
      'ipaddress' => get_client_ip(0 , TRUE),
      'create_time' => date('Y-m-d H:i:s')
    );

    //计算分数
    $data['point'] = mt_rand($take_award_data['min_point'], $take_award_data['max_point']);
    
    //取随机软文
    $WxEventCupidAwardText = WxEventCupidAwardTextService::instance();
    $data['award_text'] = $WxEventCupidAwardText->get_rand_by_award($take_award_data['id']);
    
    //取分享文字
    $WxEventCupidBeauty = WxEventCupidBeautyService::instance();
    $beauty_data = $WxEventCupidBeauty->get_by_id($beauty_id);
    $data['beauty_id'] = $beauty_id ;
    
    //分享文字
    $share_text = str_replace('{true_name}', $beauty_data['true_name'] , $event_data['share_text']);
    $share_text = str_replace('{name}', $beauty_data['name'] , $share_text );
    $share_text = str_replace('{point}' , $data['point'] , $share_text );
    $data['share_text'] = $share_text ;
    
    return $data;
  }
    
  function test_beauty( $mer_id , $event_id , $user_id , $beauty_id ) {
    //取活动
    $event_data = $this->get_by_id($event_id);
    
    $check_time_ret = $this->_check_time($event_data);
    if ( !$check_time_ret['status'] ) {
      return $check_time_ret ;
    }

    $check_times_ret = $this->_check_times($event_data , $user_id );
    if ( !$check_times_ret['status'] ) {
      return $check_times_ret ;
    }
    
    //开始抽奖
    $WxEventCupidAward = WxEventCupidAwardService::instance();
    $award_data = $WxEventCupidAward->get_by_cond(array(
      'event_type' => $this->type ,
      'event_id' => $event_id ,
      'have_remain' => 1 ,
    ));
    
    if ( empty( $award_data ) ) {
      return ajax_arr('奖品已经领完了');
    }
    
    //检查奖品 获得中奖率
    foreach( $award_data as $key => $row ) {
      $award_data[$key]['take_rate'] = $row['take_rate'] > 0 ? $row['take_rate'] : $row['remain_qty'] ;
    }
    
    //取中奖奖品
    $take_award_data = $this->get_rand($award_data);
    if ( empty( $take_award_data ) ) {
      return ajax_arr('抽取错误，请稍后再试');
    }

    //准备抽奖结果
    $event_user_data = $this->_prepare_user_data($event_data, $take_award_data, $beauty_id);
    $event_user_data['user_id'] = $user_id ;

    //处理抽奖结果
    $WxEventCupidUser = M('WxEventCupidUser');
    $WxEventCupidUser->startTrans();
    //减少奖品数量
    $sql1 = 'update wx_event_cupid set total_take_user = total_take_user + 1 where id = ' . $event_id ;
    $sql2 = 'update wx_event_cupid_award set taken_qty = taken_qty + 1 , remain_qty = remain_qty - 1 where id = ' . $take_award_data['id'] ;
    $sql3 = 'update wx_event_cupid_beauty set hot = hot + 1 where id = ' . $beauty_id ;
    
    //更新活动状态
    $ret1 = $WxEventCupidUser->execute( $sql1 ); 
    //echo $WxEventUser->_sql();
    //更新奖品信息
    $ret2 = $WxEventCupidUser->execute( $sql2 );
    
    //更新奖品信息
    $ret3 = $WxEventCupidUser->execute( $sql3 ); 
    //添加用户参与用户
    $ret4 = $WxEventCupidUser->add( $event_user_data );
    if ( $ret1 && $ret2 && $ret3 && $ret4 ) {
      $WxEventCupidUser->commit();
      return ajax_arr('ok' , TRUE , array(
        'event_user_id' => $ret4  
      ));
    } else {
      $WxEventCupidUser->rollback();
      return ajax_arr('系统错误，请稍后再试');
    }

  }
  
  /**
   * 抽奖
   * @param type $pro_arr
   * @return type
   */
  function get_rand($pro_arr) {
    $result = '';
    $pro_sum = 0 ;
    
    //概率数组的总概率精度
    foreach ( $pro_arr as $row ) {
      $pro_sum += $row['take_rate'];
    }
    //概率数组循环   
    foreach ($pro_arr as $key => $val) {
      $rand_num = mt_rand(1, $pro_sum);
      if ($rand_num <= $val['take_rate']) {
        $result = $pro_arr[$key];
        break;
      } else {
        $pro_sum -= $val['take_rate'] ;
      }
    }
    unset($pro_arr);
    return $result;
  }
}
